package com.jkl.nettyserver.Tool.Zookeeper;

import com.jkl.nettyserver.Config.ZookeeperConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class  ZookeeperClient implements DisposableBean {
    final ZookeeperConfig zookeeperConfig;
    private final CuratorFramework curatorFramework;
    private String servicePath;

    @Autowired
    public  ZookeeperClient(ZookeeperConfig zookeeperConfig, CuratorFramework curatorFramework) {
        this.zookeeperConfig = zookeeperConfig;
        this.curatorFramework = curatorFramework;
    }

    @PostConstruct
    public void init() {
        try {
            ensurePathExists(zookeeperConfig.getRootNode());
        } catch (Exception e) {
            log.error("Failed to initialize ZooKeeper path", e);
        }
    }

    private void ensurePathExists(String path) throws Exception {
        if (curatorFramework.checkExists().forPath(path) == null) {
            curatorFramework.create().creatingParentsIfNeeded().forPath(path);
        }
    }

    public void register(String address) {
        servicePath = zookeeperConfig.getRootNode() +address;
        try {
            curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(servicePath);
            curatorFramework.setData().forPath(servicePath,String.valueOf(0).getBytes());//设置初始数据
            log.info("Service registered successfully: {}", servicePath);
        } catch (Exception e) {
            log.error("Failed to register service in ZooKeeper", e);
        }
    }

    public void addConnectCount() throws Exception {
        if (curatorFramework.checkExists().forPath(servicePath) != null) {// 检查节点是否存在
            // 如果节点存在，则更新数据
            //获取该节点的数据，并且数据+1
            byte[] data = curatorFramework.getData().forPath(servicePath);
            Integer connCount = Integer.parseInt(new String(data, StandardCharsets.UTF_8));
            connCount++;
            curatorFramework.setData().forPath(servicePath, String.valueOf(connCount).getBytes(StandardCharsets.UTF_8));
            log.info(servicePath+"-connect count-"+connCount);
        } else {
            log.error("Node does not exist. Create it first or adjust your logic.");
        }
    }
    public void reduceConnectCount() throws Exception {
        if (curatorFramework.checkExists().forPath(servicePath) != null) {// 检查节点是否存在
            // 如果节点存在，则更新数据
            //获取该节点的数据，并且数据-1
            byte[] data = curatorFramework.getData().forPath(servicePath);
            Integer connCount = Integer.parseInt(new String(data, StandardCharsets.UTF_8));
            connCount--;
            curatorFramework.setData().forPath(servicePath, String.valueOf(connCount).getBytes(StandardCharsets.UTF_8));
            log.info(servicePath+"-connect count-"+connCount);
        } else {
            log.error("Node does not exist. Create it first or adjust your logic.");
        }
    }
    // 确保在不再需要时关闭ZooKeeper连接（在类的其他部分或析构方法中）
    @PreDestroy
    public void destroy() {
        if (curatorFramework != null) {
            curatorFramework.close();
        }
    }
}